<template>
	<view>
		<u-sticky class="u-sticky">
			<view class="cu-bar search" style="padding: 10px">
				<u-search style="flex: 1;" v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描"
					:show-action="false" @search="confirmInput"></u-search>
				<view style="margin-left: 10px; display: flex; flex-direction: column">
					<u-icon @click="search" name="scan" size="50"></u-icon>
				</view>
			</view>
		</u-sticky>
		<scroll-view class="scroll-list bg-white" scroll-y="true" @scrolltolower="loadMore">
			<block v-for="(ietm,index) in visibleList" :key="index">
				<u-form class="form" :model="ietm" ref="uForm" label-position="left">
					<u-form-item :label="ietm.barTypeName + '码'" prop="snCode" label-width="120" >
						<u-input v-model="ietm.snCode" :disabled="true" type="text" di maxlength="64"></u-input>
						<u-icon name="/static/common/img/delData.png" @click="delDetail(ietm.snCode)" color="#2979ff" class="rights" size="30"></u-icon>
					</u-form-item>
				</u-form>
			</block>
			
		</scroll-view>
		<view  style="height: 65px;" ></view>
		<view class="footer">
			<view class="confrim-btn padding padding-bottom-sm  bg-white">
				<u-button type="primary" class="no-border confirm-btn" @click="submit" >确认</u-button>
			</view>
		</view>
		<js-error mode="bottom" ref="jsError" @update:errorClose="onErrorClose"></js-error>
	</view>
</template>

<script>
	import { RecycleScroller } from 'vue-virtual-scroller'
	export default {
		data() {
			return {
				list:[],
				barCode:'',
				bizKey: '',
				focus: true,
				pageSize: 10, // 每页显示的条数
				currentPage: 1, // 当前页码
				visibleList:[],// 当前可见的数据列表
				newList:{
					list:[]
				},
			}
		},
		onLoad() {
			var _this = this;
			const eventChannel = this.getOpenerEventChannel();
		    eventChannel.on('initfilter',function(info){
					console.log(info,'list')
				if (info && info.list) {
					_this.list = info.list;
					_this.list.forEach(item => {
						item.id = item.snCode; // 确保item和item.snCode存在
					});
					_this.visibleList = _this.list.slice(0, _this.pageSize);
					_this.newList.list = info.list;
				}
				_this.bizKey = info.bizKey;


				// _this.list = info.list;
				// _this.list.length > 0 && _this.list.forEach(item=>{
				// 	item.id = item.snCode
				// })
				// setTimeout(()=>{
				// 	_this.visibleList = _this.list.slice(0, _this.pageSize);
				// })
				// _this.newList.list = info.list;
				// _this.bizKey = info.bizKey
			});
			console.log('bizKey',_this.bizKey)
		},
		methods: {
			loadMore() {
				const nextPage = this.currentPage + 1;
				const nextItems = this.list.slice(this.pageSize * (nextPage - 1), this.pageSize * nextPage);
				if (nextItems.length > 0) {
					this.visibleList = this.visibleList.concat(nextItems);
					this.currentPage = nextPage;
				}
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500);
			},
			search() {
				var _that = this;
				_that.focus = false
				// #ifdef APP-PLUS
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
				mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
					'scanType': ['qrCode', 'barCode'],
					// 是否隐藏相册，默认false不隐藏
					'hideAlbum': false,
					//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
					'language': 'en',
					//相册选择照片识别错误提示(ios)
					'failedMsg': '未识别到二维码，请重试',
					//Android支持全屏需要设置此参数
					'screenType': 'full'
				},
					async (ret) => {
						console.log('ret', ret)
						if (ret.resp_message == 'success') {
							_that.barCode = ret.resp_result;
							
							await _that.getDeleteCache(ret.resp_result)
						}
					})
				// #endif
				// #ifdef H5 || MP-WEIXIN || MP-QQ 
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					success: async (res) => {
						_that.barCode = res.result;
			
						await _that.getDeleteCache(res.result)
					}
				})
				// #endif
			},
			async confirmInput() {
				this.focus = false
				console.log(this.barCode, 'barCode')
				await this.getDeleteCache(this.barCode)
			},
			delDetail(item) {
				let that = this
				uni.showModal({
					title: '删除提示',
					content: '是否删除此记录？',
					confirmColor: '#F54E40',
					success: async (res) => {
						if (!res.confirm) {
							return false;
						}
						await this.getDeleteCache(item)
						
					}
				})
			},
			async getDeleteCache(barCode){
				var _this = this;
				var list = _this.list;
				
				
				
			
				// const { bizKey } = list[itemIndex];
				const bizKey = this.bizKey
				
				const response = await this.$u.api.zgz.sendRemoveCache({ barCode, bizKey });
				if (response.result === 'true') {
					
					const itemIndex = list.findIndex(item => item.snCode === response.data.barCode);
					if (itemIndex === -1) {
						setTimeout(()=>{
							this.barCode = '';
							this.makeSound("bcz");
						},500)
						if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
							this.handleFocus()
						}
						return;
					}
					_this.list = _this.list.filter(item => item.snCode !== response.data.barCode)
					_this.visibleList = _this.visibleList.filter(item => item.snCode !== response.data.barCode)
					console.log('visibleList',_this.visibleList)
					_this.newList.list = response.data.resendList
					this.barCode = ''
					this.makeSound("cg");
					
				}else{
					setTimeout(()=>{
						this.barCode = '';
						this.makeSound("sb");
					},500)
					this.$refs.jsError.showError('', response.message, 'error');
				}
				
			// 	const response = await this.$u.api.zgz.deleteCache({ bizKey, barCode });
			
			// 	const itemIndex = list.findIndex(item => item.barCode === response.data.barCode);
			
			// 	if (itemIndex === -1) {
			// 		setTimeout(()=>{
			// 			this.barCode = '';
			// 			this.makeSound("bcz");
			// 		},500)
			// 		this.$refs.jsError.showError('', '当前码不存在', 'error');
			// 		if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
			// 			this.handleFocus()
			// 		}
			// 		return;
			// 	}
			// 	if (response.result === 'true') {
			// 		if(response.data.boxType === _this.vuex_config.xiangPrefix){
			// 					// 数量加1
			// 			_this.xiangNums--
			// 			const xcodesArray = _this.xcodes.split(',');
			// 			const FilterXcodesArray = xcodesArray.filter(item => item !== barCode)
					
			// 			_this.xcodes = FilterXcodesArray.join(',')
					
			// 		}else if(response.data.boxType === _this.vuex_config.guanPrefix){
			// 			// 数量加1
			// 			_this.guanNums--
			// 			const xcodesArray = _this.gcodes.split(',');
			// 			const FilterXcodesArray = xcodesArray.filter(item => item !== barCode)
			// 			_this.gcodes = FilterXcodesArray.join(',')
			// 		}
			// 		list.splice(itemIndex,1);
			// 		setTimeout(()=>{
			// 			this.barCode = '';
			// 			this.makeSound("cg");
			// 		},500)
			// 	} else {
			// 		setTimeout(()=>{
			// 			this.barCode = '';
			// 			this.makeSound("sb");
			// 		},500)
			// 		this.$refs.jsError.showError('', response.message, 'error');
			// 	}
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					this.handleFocus()
				}
				_this.$forceUpdate()
			},
			//提交
			async submit(){
				console.log('submit')
				if(!this.bizKey){
					uni.navigateBack();
				}else{
					
					const response = await this.$u.api.zgz.sendResend({ bizKey : this.bizKey });
					if(response.result === "true" && response.data.status == 200){
						this.newList.resendList = response.data.resendList
						this.newList.sendList = response.data.sendList
						this.newList.qtyList = response.data.qtyList
						this.newList.resendQtyList = response.data.resendQtyList
						const eventChannel = this.getOpenerEventChannel();
						eventChannel.emit('Filter', this.newList);
						uni.navigateBack();
					}else{
						this.$refs.jsError.showError('',response.message,'error');
						return;
					}
				}
				
				

				
				// setTimeout(() => {
				//     const eventChannel = this.getOpenerEventChannel();
				// 	console.log('list',this.list)
				//     eventChannel.emit('Filter', this.list);
			 //    }, 300);
				
			},
			//页面删除数据
			delData(code){
				var _this = this;
				var list = _this.list;
				for(var i = 0 ; i < list.length ; i++ ){
					if(list[i].code == code){
						if(list[i].code.length == 24){
							_this.num = parseInt(_this.num) - 1;
							_this.qty = parseInt(_this.qty) - parseInt(list[i].quty);
						}
						list.splice(i,1);
					}
				}
			},
			onErrorClose(result) {
				console.log('result',result)
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
						this.focus = true;
					}
				}, 100);
			 
			},
			makeSound(name){
				console.log("=====testClick=====");
				let src = '/static/jeesite/'+name+'.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
		}
	}
</script>

<style>
@import '../../btdm.css';
.scroll-list {
	height: calc(100vh - var(--window-top) - var(--window-bottom) - 65px);
	width: 100%;
}
.scroller {
  height: 100%; /* 设置滚动容器的高度 */
}
.list-item {
  height: 100rpx; /* 每个列表项的高度 */
}
</style>
